module(..., package.seeall)

local mouse = require "moaix.input.mouse"
local touch = require "moaix.input.touch"


tap_count    = 0
tap_last_t   = 0
tap_interval = 0.25

function to_touch_down() 
    local t = MOAISim.getElapsedTime()
    if t - tap_last_t > tap_interval then
        tap_count = 0
    end
    tap_count  = tap_count + 1
    tap_last_t = t
    touch.touch_handler(MOAITouchSensor.TOUCH_DOWN, 1, x, y, tap_count)
end

function to_touch_move() 
    if mouse.left then 
        touch.touch_handler(MOAITouchSensor.TOUCH_MOVE, 1, x, y, tap_count)
    end 
end

function to_touch_up() 
    touch.touch_handler(MOAITouchSensor.TOUCH_UP, 1, x, y, tap_count)
end


----------------------------------------------------------------------------------------------------
listeners = {}

function start_touch_emulation()
    --[[ This function sets up listeners to make the mouse emulate a touch screen (although its 
    single touch in this implementation). ]]
    if #listeners == 0 then
        table.insert(listeners, mouse.channel:listen(mouse.SIGNALS.LEFT_PRESS,   to_touch_down))
        table.insert(listeners, mouse.channel:listen(mouse.SIGNALS.LEFT_RELEASE, to_touch_up))
        table.insert(listeners, mouse.channel:listen(mouse.SIGNALS.MOVE,         to_touch_move))
    end
end

function stop_touch_emulation()
    for _, listener in ipairs(listeners) do
        listener:stop()
    end
    listeners = {}
end
